/*
===========================================================================
Copyright (C) 2013-2014 Avotu Briezhaudzetava

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.

===========================================================================
*/

//
// database.cpp (main.cpp is too crowded)
//

//
// includes
//
#include "main.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDir>

/*
================
loadDatabase
================
*/
void Main::loadDatabase() {
#ifdef Q_OS_UNIX
    this->setDatabaseDirectory( QDir::homePath() + "/.precursorLogger/" );
#else
    this->setDatabaseDirectory( QDir::currentPath() + "/" );
#endif

    // make path id nonexistant
    QDir dir( this->databaseDirectory());
    if ( !dir.exists()) {
        dir.mkpath( this->databaseDirectory());
        if ( !dir.exists()) {
            this->error( StrFatalError + this->tr( "could not create database path\n" ));
            return;
        }
    }

    // create database
    this->setDatabaseFilename( this->databaseFilename() + Common::defaultDBFilename );
    QFile database( this->databaseFilename());
    QSqlDatabase db;

    // failsafe
    if ( !db.isDriverAvailable( "QSQLITE" ))
        this->error( StrFatalError + this->tr( "sqlite not present on the system\n" ));

    // set sqlite driver
    db = QSqlDatabase::addDatabase( "QSQLITE" );

    // touch file if empty
    if ( !database.exists()) {
        database.open( QFile::WriteOnly );
        database.close();
    }

    // set path and open
    db.setDatabaseName( this->databaseFilename());
    if ( !db.open())
        this->error( StrFatalError + this->tr( "could not load task database\n" ));

    // create query
    QSqlQuery query;

    // create initial table structure (if non-existant)
    if ( !query.exec( "create table if not exists precursors ( id integer primary key, title varchar( 64 ) unique, density float, baseAmount float, units integer, lot varchar( 32 ) unique, solvent integer )" ) ||
         !query.exec( "create table if not exists users ( id integer primary key, name varchar( 64 ) unique, password varchar( 32 ) not null, flags integer )" ) ||
         !query.exec( "create table if not exists templates ( id integer primary key, name varchar( 128 ) unique, purpose varchar( 128 ), amount float )" ) ||
         !query.exec( "create table if not exists logs ( id integer primary key, precursorId integer, userId integer, amount float, date varchar( 6 ), purpose varchar( 128 ), units integer )" )) {
        this->error( StrFatalError + this->tr( "could not create internal database structure, reason - \"%1\"\n" ).arg( query.lastError().text()));
    }

    // TODO: add paswordless admin by default


    // load precursors & logs
    this->loadPrecursors();
    this->loadLogs();
    this->loadUsers();
}

/*
================
removeOrphanedLogs
================
*/
void Main::removeOrphanedLogs() {
    // create query
    QSqlQuery query;

    // remove orphaned logs (fixes crash with invalid teamId/taskId)
    if ( !query.exec( "delete from logs where precursorId not in ( select id from precursors )" ))
        this->error( StrSoftError + QString( "could not delete orphaned logs, reason: %1\n" ).arg( query.lastError().text()));
}
